package algorithm.leetcode;

/**
 * 给定一个 32 位有符号整数，将整数中的数字进行反转。
 * <p>
 * 示例 1:
 * <p>
 * 输入: 123
 * 输出: 321
 * 示例 2:
 * <p>
 * 输入: -123
 * 输出: -321
 * 示例 3:
 * <p>
 * 输入: 120
 * 输出: 21
 *
 * @author: zhouj-j
 * @since: 2018/7/4
 */
public class __007_reverse {
    public int reverse(int x) {
        int v, flag;
        if (x < 0) {
            v = x * -1;
            flag = -1;
        } else {
            v = x;
            flag = 1;
        }
        if (v < 0) {
            return 0;
        }
        int ret = 0;
        int threshold = 214748364;
        int last = 7;
        while (true) {
            int p = v % 10;
            if (ret > threshold) {
                return 0;
            } else if (ret == threshold && p > last) {
                return 0;
            }

            ret = ret * 10 + p;
            v = v / 10;
            if (v == 0) {
                break;
            }
        }
        if (ret < 0) {
            return 0;
        }
        return ret * flag;
    }

    public static void main(String[] args) {
        System.out.println(new __007_reverse().reverse(-2147483648));
    }
}
